package com.springmvc.netty.server.websocket;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.beans.factory.annotation.Autowired;

import com.springmvc.utils.SpringUtils;
import com.springmvc.utils.majiang.ChannelUtil;
import com.springmvc.utils.majiang.RoomUtil;
import com.springmvc.web.majiang.entity.User;
import com.springmvc.web.majiang.service.IUserService;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.handler.codec.http.HttpVersion;

public class HttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

	@Autowired
	IUserService		 userService = (IUserService) SpringUtils.getBean(IUserService.class);

	private final String wsUri;

	public HttpRequestHandler(String wsUri) {
		super();
		this.wsUri = wsUri;
	}

	@Override
	public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
		if ("/bad-request".equalsIgnoreCase(request.uri())) {
			ctx.fireChannelRead(request.retain()); // 2
		} else if (wsUri.equalsIgnoreCase(request.uri())) {
			ctx.fireChannelRead(request.retain()); // 2
		} else {
			if (HttpUtil.is100ContinueExpected(request)) {
				send100Continue(ctx); // 3
			}
			Map<String, String> parmMap = new RequestParser(request).parse(); // 将GET, POST所有请求参数转换成Map对象

			System.out.println(parmMap);
			System.out.println("uri:" + request.uri());

			System.out.println("remoteAddress:" + ctx.channel().remoteAddress());

			Channel channel = ctx.channel();
			User entity = new User();
			Long userid = Long.valueOf(parmMap.get("userid"));
			Long roomid = Long.valueOf(parmMap.get("roomid"));
			Integer position = Integer.valueOf(parmMap.get("position"));
			entity.setId(userid);
			entity.setRoomid(roomid);
			entity.setChannelid(channel.id().asLongText());
			entity.setRemoteaddress(channel.remoteAddress().toString());
			entity.setUpdatetime(new Date());
			userService.updateById(entity);

			ChannelUtil.setChannel(userid, channel);

			RoomUtil.setRoomUser(userid, roomid, position);

			ctx.fireChannelRead(request.setUri(wsUri).retain());
		}
	}

	private static void send100Continue(ChannelHandlerContext ctx) {
		FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE);
		ctx.writeAndFlush(response);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		Channel incoming = ctx.channel();
		System.out.println("Client:" + incoming.remoteAddress() + "异常");
		// 当出现异常就关闭连接
		cause.printStackTrace();
		ctx.close();
	}
}